﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MvcShop.Models.Services
{
    public interface IKeyWordService
    {
        void Add(SearchKeyWord keyWord);
        void SetKeyWordTimes(string keyWord);
        IEnumerable<string> GetDefaultHotKeyWord();
        IEnumerable<string> FindLikeKeyWords(string keyword);
    }

    public class KeyWordService : ServiceBase,IKeyWordService
    {

        #region IKeyWordService 成员

        public void Add(SearchKeyWord sKeyWord)
        {
            using (this.dataContext)
            {
                this.dataContext.AddToSearchKeyWords(sKeyWord);
                this.dataContext.SaveChanges();
            }
        }

        public void SetKeyWordTimes(string keyWord)
        {
            using (this.dataContext)
            {
                var keyword = this.dataContext.SearchKeyWords.FirstOrDefault(c => c.KeyWord == keyWord);
                if (keyword != null)
                {
                    keyword.SearchTimes += 1;
                    this.dataContext.SaveChanges();
                }
                else
                {
                    keyword = new SearchKeyWord { KeyWord = keyWord, SearchTimes = 1 };
                    Add(keyword);
                }
            }
        }

        public IEnumerable<string> GetDefaultHotKeyWord()
        {
            var query = (from kw in this.dataContext.SearchKeyWords
                         orderby kw.SearchTimes descending
                         select kw.KeyWord).Take(15).ToList();
            return query;
        }

        public IEnumerable<string> FindLikeKeyWords(string keyword)
        {
            var query = (from kw in this.dataContext.SearchKeyWords
                         where kw.KeyWord.StartsWith(keyword)
                         orderby kw.SearchTimes descending
                         select kw.KeyWord).Take(10).ToList();
            return query;
        }

        #endregion
    }
}
